<script lang="ts" setup>
import { ref } from 'vue'
// import { ELPagination } from 'element-plus'
import RoleService from '@/api/role'
import PermissionService from '@/api/permission'
import { ListToTree } from '@/utils/listToTree'

const roleList = ref([] as any)
const pageParams = ref({
  page: 1,
  pagesize: 5,
  total: 0
})
const formData = ref({
  name: '',
  description: '',
  state: 0
})
const showDialog = ref(false)
const roleRef = ref()
const dialogRules = {
  name: [
    { required: true, message: '角色名称不能为空', trigger: 'blur' },
    {
      min: 2,
      max: 10,
      message: '角色名称的长度为2-10个字符',
      trigger: 'blur'
    }
  ],
  description: [
    { required: true, message: '角色描述不能为空', trigger: 'blur' },
    {
      min: 1,
      max: 100,
      message: '角色描述的长度为1-100个字符',
      trigger: 'blur'
    }
  ]
} as any

const getRoleList = async () => {
  const res: any = await RoleService.getRoleListService(pageParams.value)
  roleList.value = res.rows
  pageParams.value.total = res.total
  // 针对角色列表每行数据添加一个编辑标记
  roleList.value.forEach((item: any) => {
    item.isEdit = false
    item.editRow = {
      name: item.name,
      description: item.description,
      state: item.state
    }
  })
}
getRoleList()

// 切换分页时请求数据
const pageChange = (newPage: any) => {
  pageParams.value.page = newPage
  getRoleList()
}

// 确定
const confirm = async () => {
  await roleRef.value.validate()
  await RoleService.addRoleService(formData.value)
  ElMessage.success('新增角色成功')
  getRoleList()
  cancel()
}
const cancel = () => {
  roleRef.value.resetFields()
  showDialog.value = false
}

// 编辑行
const editRow = (row: any) => {
  row.isEdit = true
  row.editRow.name = row.name
  row.editRow.description = row.description
  row.editRow.state = row.state
}
const editConfirm = async (row: any) => {
  console.log(row.editRow.name)
  if (row.editRow.name && row.editRow.description) {
    await RoleService.updateRoleService({ ...row.editRow, id: row.id })
    ElMessage.success('更新角色成功')
    // 显示数据，退出编辑状态
    Object.assign(row, { ...row.editRow, isEdit: false })
  } else {
    ElMessage.error('请填写角色名称与描述')
  }
}

// 分配权限
const permissionData = ref([] as any) // 权限列表
const currentRoleId = ref(null as any) // 当前角色id
const permIds = ref([] as any) // 回显
const btnPermission = async (id: any) => {
  currentRoleId.value = id
  var res: any = await PermissionService.getPermissionListService()
  permissionData.value = ListToTree(res, 0)
  var resRole: any = await RoleService.getRoleDetailService(id)
  permIds.value = resRole.permIds
  showPermissionDialog.value = true
}

// 确定删除
const confirmDelete = async (id: any) => {
  await RoleService.deleteRoleService(id)
  ElMessage.success('删除角色成功')
  getRoleList()
}

// 弹层
const showPermissionDialog = ref(false)
const treeRef = ref()
// 确定分配权限
const btnPermissionOk = async () => {
  await RoleService.assignPermService({
    id: currentRoleId.value,
    permIds: treeRef.value.getCheckedKeys()
  })
  ElMessage.success('角色分配权限成功')
  showPermissionDialog.value = false
}
</script>
<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="roleList">
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.name"
              size="small"
            ></el-input>
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <!-- 自定义结构 -->
          <template #default="{ row }">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
            <span v-else>{{ row.state == 1 ? '已启用' : '禁用' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template #default="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.description"
              size="small"
              type="textarea"
            ></el-input>
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{ row }">
            <!-- 区分编辑状态显示 -->
            <template v-if="row.isEdit">
              <el-button @click="editConfirm(row)">确定</el-button>
              <el-button @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button
                size="small"
                type="primary"
                text
                @click="btnPermission(row.id)"
                >分配权限</el-button
              >
              <el-button size="small" type="primary" text @click="editRow(row)"
                >编辑</el-button
              >
              <el-popconfirm
                @confirm="confirmDelete(row.id)"
                title="确定要删除吗?"
              >
                <template #reference>
                  <el-button size="small" type="primary" text>删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" style="height: 60px" align="middle" justify="end">
        <el-pagination
          background
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          layout="prev, pager, next"
          @current-change="pageChange"
        />
      </el-row>
      <!-- 放置弹层，添加角色 -->
      <el-dialog
        @close="cancel"
        title="添加角色"
        v-model="showDialog"
        width="500px"
      >
        <el-form
          ref="roleRef"
          :model="formData"
          :rules="dialogRules"
          label-width="120px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input
              v-model="formData.name"
              size="small"
              style="width: 300px"
            />
          </el-form-item>
          <!-- 如果需要校验，需要prop属性 -->
          <el-form-item label="是否启用" prop="state">
            <el-switch
              v-model="formData.state"
              :active-value="1"
              :inactive-value="0"
              size="small"
            ></el-switch>
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input
              v-model="formData.description"
              size="small"
              type="textarea"
            />
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="confirm"
              >确定</el-button
            >
            <el-button size="small" @click="cancel">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <!-- 放置权限弹层 -->
    <el-dialog v-model="showPermissionDialog">
      <!-- 放置权限数据 -->
      <el-tree
        ref="treeRef"
        node-key="id"
        check-strictly
        :data="permissionData"
        show-checkbox
        default-expand-all
        :default-checked-keys="permIds"
        :props="{ label: 'name' }"
      />

      <template #footer>
        <el-row>
          <el-col>
            <el-button size="small" type="primary" @click="btnPermissionOk"
              >确定</el-button
            >
            <el-button size="small" @click="showPermissionDialog = false"
              >取消</el-button
            >
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.role-operate {
  padding: 10px;
}
</style>
